<?php
namespace app\controller\admin;

use app\BaseController;
use think\facade\Request;

use app\model\OrderModel;
// use think\Image;
use app\model\tool\ImageModel;

class order extends BaseController{

    public function index(){

        $filter = [
            'customer'      =>  $_GET['customer']??'',
            'status'        =>  $_GET['status']??'',
            'order_no'      =>  $_GET['order_no']??'',
            'start_time'    =>  $_GET['start_time']??'',
            'end_time'      =>  $_GET['end_time']??'',
        ];
        $list = OrderModel::get_list( $filter );
        $total = OrderModel::get_order_count();
        return json( [
            'list'  => $list,
            'total' => $total,
        ] );

    }

    /**
     * 导出 excel
     */
    public function export(){

        global $_W;
        $filter = [
            'customer'      =>  $_GET['customer']?:'',
            'status'        =>  $_GET['status']?:'',
            'order_no'      =>  $_GET['order_no']?:'',
            'start_time'    =>  $_GET['start_time']?:'',
            'end_time'      =>  $_GET['end_time']?:'',
        ];
        $list = OrderModel::get_list( $filter, 1 );

        require_once IA_ROOT . '/addons/sm_shop/lib/PHPExcel.php';
        $objPHPExcel = new \PHPExcel();
        // Set document properties
//        echo date('H:i:s') , " Set document properties" ;

        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("PHPExcel Test Document")
            ->setSubject("PHPExcel Test Document")
            ->setDescription("Test document for PHPExcel, generated using PHP classes.")
            ->setKeywords("office PHPExcel php")
            ->setCategory("Test result file");


// Add some data
//        echo date('H:i:s') , " Add some data" ;
//        $objPHPExcel->setActiveSheetIndex(0)
//            ->setCellValue('A1', 'Hello')
//            ->setCellValue('B2', 'world!')
//            ->setCellValue('C1', 'Hello')
//            ->setCellValue('D2', 'world!');

// Miscellaneous glyphs, UTF-8
//        $objPHPExcel->setActiveSheetIndex(0)
//            ->setCellValue('A4', 'Miscellaneous glyphs')
//            ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');


//        $objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
//        $objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
//        $objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);


//        $value = "-ValueA\n-Value B\n-Value C";
//        $objPHPExcel->getActiveSheet()->setCellValue('A10', $value);
//        $objPHPExcel->getActiveSheet()->getRowDimension(10)->setRowHeight(-1);
//        $objPHPExcel->getActiveSheet()->getStyle('A10')->getAlignment()->setWrapText(true);
//        $objPHPExcel->getActiveSheet()->getStyle('A10')->setQuotePrefix(true);

        $title_list = [
            'order_no'      => '订单号',
            'goods'         => '商品',
            'customer_name' => '客户名称',
            'address_name'  => '收货人',
            'address_phone' => '收货人电话',
            'status_text'   => '订单状态',
            'is_payed'      => '支付',
            'total'         => '总计',
            'create_time'   => '日期',
        ];
        $activeSheet = $objPHPExcel->setActiveSheetIndex(0);
        $current_row = 1;
        $activeSheet->setCellValue('A'. $current_row, $title_list['order_no']);
        $activeSheet->setCellValue('B'. $current_row, $title_list['customer_name']);
        $activeSheet->setCellValue('C'. $current_row, $title_list['address_phone']);
        $activeSheet->setCellValue('D'. $current_row, $title_list['status_text']);
        $activeSheet->setCellValue('E'. $current_row, $title_list['is_payed']);
        $activeSheet->setCellValue('F'. $current_row, $title_list['total']);
        $activeSheet->setCellValue('G'. $current_row, $title_list['create_time']);
        $activeSheet->setCellValue('H'. $current_row, $title_list['goods']);
        $current_row++;


        foreach( $list as $value ){

            $activeSheet->setCellValue('A'. $current_row, $value['order_no']);
            $activeSheet->setCellValue('B'. $current_row, $value['customer_name']);
            $activeSheet->setCellValue('C'. $current_row, $value['address_phone']);
            $activeSheet->setCellValue('D'. $current_row, $value['status_text']);
            $activeSheet->setCellValue('E'. $current_row, $value['is_payed']?'已支付':'未支付');
            $activeSheet->setCellValue('F'. $current_row, $value['total']);
            $activeSheet->setCellValue('G'. $current_row, $value['create_time']);
            $activeSheet->setCellValue('H'. $current_row, $value['goods']);
            $current_row++;


        }


// Rename worksheet
//        echo date('H:i:s') , " Rename worksheet" ;
        $objPHPExcel->getActiveSheet()->setTitle('Simple');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);


// Save Excel 2007 file
//        echo date('H:i:s') , " Write to Excel2007 format" ;
//        $callStartTime = microtime(true);

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $excel_name = 'order-' . date('YmdHis'). '.xlsx';
//        $excel_path =  '/attachment/excel/' . $_W['uniacid'] . '/' . $excel_name;
        $excel_path =  '/attachment/' . $excel_name;
        try{
            $objWriter->save( IA_ROOT . $excel_path );
        }catch( \Exception $error ){

            return json([
                'status'=>1,
                'description'=> $error->getMessage()
            ]);
            die();
        }



        $download_url = $_W['siteroot'] .  ltrim( $excel_path,'/' );
//        http_redirect( $excel_url );

        return json([
            'status'        => 0,
            'download_url'  => $download_url
        ]);
//        $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
//        $callEndTime = microtime(true);
//        $callTime = $callEndTime - $callStartTime;

//        echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) ;
//        echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" ;
// Echo memory usage
//        echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" ;

//        return json( $list );

    }


    /**
     * 获取单条 订单信息
     */
    public function info(){

        $order_id = $_GET['id'];
        $order_info = OrderModel::get_order( $order_id );

        foreach( $order_info['goods'] as &$goods ){

            $goods['image'] = ImageModel::resize2($goods['image'], 100, 100 );
        }

        $order_info['payment_method_text'] = $order_info['payment_method'] == 'wechat'?'微信支付':'';
        $order_info['payment_method_text'] = $order_info['payment_method'] == 'alipay'?'支付宝':$order_info['payment_method_text'];

        if( $order_info['shipping_method'] == 'package' ){
            $order_info['shipping_method_text'] = count($order_info['package']) ?$order_info['package'][0]['name']:'其他快递';
        }else if( $order_info['shipping_method'] == 'pickup' ) {
            $order_info['shipping_method_text'] = '自提订单';
        }

        $code_text = [
            'coupon'    => '优惠券',
            'goods'     => '商品',
            'shipping'  => '配送',
            'total'     => '总计',
        ];
        foreach( $order_info['total'] as &$total ){

            $total['code_text'] = $code_text[ $total['code'] ];
            
        }
        $order_info['message'] = trim( $order_info['message'] );
        return json( $order_info );

    }

    public function status_list(){

        $order_all_status = OrderModel::get_all_status();

        return json( $order_all_status );
    }

    //todo 改变订单状态(添加订单历史)
    public function add_history(){

        $order_id = Request::param('order_id');
        // $order_id = $_GET['order_id'];

        // $order_status = $_POST['order_status'];
        $order_status = Request::param('order_status');
        // $comment = $_POST['comment'];
        $comment = Request::param('comment');

        $data = [
            'order_status'=>$order_status,
            'comment'=>$comment,
            'create_time'=>date("Y-m-d H:i:s")
        ];
        $ret = OrderModel::add_history( $order_id, $data );


        return json( [
            'status'    => 0,
            'ret'       => $ret,
            // 'order_id'       => $order_id
        ] );

    }

    public function set_order_package(){

        $res = [
            'status' => 0
        ];

        $order_id = Request::param('order_id');
        $package_no = Request::param('package_no');
        $express_code = Request::param('express_code');
        // $order_id = $_GET['order_id'];
        // $package_no = $_POST['package_no'];
        // $express_code = $_POST['express_code'];

        $data = [
            'package_no'=>$package_no,
            'express_code'=>$express_code,
        ];


        OrderModel::removePackage( $order_id );
        $res['ret'] = OrderModel::addPackage( $order_id, $data );

        $history_data = [
            'order_status'=>'shipping',
            'comment'=>'确定发货',
            'create_time'=>date("Y-m-d H:i:s")
        ];
        OrderModel::add_history( $order_id, $history_data );

        return json( $res );

    }

    // todo 退款操作
    public function refund(){

        global $_GPC;
        // todo 退款操作

        $json = [

            'status'=>0,

        ];
        if( empty( $_GPC['order_id'] ) ){
            $json['status'] = 1;
            $json['description'] = '参数不合法';
            return json( $json );
            die();
        }

        $order_id = $_GPC['order_id'];
        $order = OrderModel::get_order( $order_id );

        if( empty( $order ) ){
            $json['status'] = 1;
            $json['description'] = '订单不存在.';
            return json( $json );
            die();
        }


        //首先load模块函数
        load()->model('refund');

        //创建退款订单
        //$tid  模块内订单id
        //$module 需要退款的模块
        //$fee 退款金额
        //$reason 退款原因
        //成功返回退款单id，失败返回error结构错误

        $tid = 'order-' . $order['order_no'];
        $module = $_GPC['m'];
        $fee = $_GPC['fee']?:'';
        $reason = $_GPC['reason']?:'';

        $refund_id = refund_create_order($tid, $module, $fee, $reason);
        if (is_error($refund_id)) {
//            itoast($refund_id['message'], referer(), 'error');
            $json['status'] = 1;
            $json['description'] = $refund_id['message'];
            return json( $json );
            die();
        }

        //发起退款
        $refund_result = refund( $refund_id );
        if (is_error($refund_result)) {
//            itoast($refund_result['message'], referer(), 'error');
            $json['status'] = 1;
            $json['description'] = $refund_result['message'];
            return json( $json );
            die();
        } else {
            pdo_update('core_refundlog', array('status' => 1), array('id' => $refund_id));

            // todo 更改订单状态 到已取消

            $refund_data = [
                'order_id'=>$order_id,
                'reason'=>$reason
            ];
            $ret = OrderModel::refund( $refund_data );
            // todo 更改支付状态 到已退款
            $json['ret'] = $ret;
            $json['description'] = '退款成功';
            return json( $json );
            die();

        }




    }

}
